<template>
  <div class="chart_room">
    <div class="left">
      <div class="left_header">
        <img :src="user_img"
             alt="用户头像">
        <h3>{{ username }}</h3>
      </div>
      <ul class="left_list"
          ref="list">
        <router-link v-for="(item,i) in contact_list"
                     :key="item.chatTime"
                     :to="{path:'/chat',query:{chat_name:item.userOne==username?item.userTwo:item.userOne}}"
                     tag='li'
                     @click.native="update(item,i)">
          <img :src="item.userOne==username?item.imgTwo:item.imgOne"
               alt="">
          <span>{{item.userOne==username?item.userTwo:item.userOne}}</span>
        </router-link>
      </ul>
    </div>
    <div class="right">
      <div class="right_header">
        <img :src="chat_img"
             alt="用户头像">
        <h3>{{ chat_name }}</h3>
      </div>
      <div class="right_container"
           ref="right_container">
        <div class="content clearfix"
             ref="container"></div>
      </div>
      <div class="right_input">
        <textarea class="input_textarea"
                  v-model="content"></textarea>
        <button class="input_btn"
                @click="submit">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      content: '', // 聊天内容
      username: '', // 用户名
      chat_name: '', // 对方
      user_img: '', // 用户头像
      chat_img: '', // 对方头像
      chat_room: '', // 房间名
      record: [], // 聊天记录
      contact_list: [], // 联系人列表
    }
  },
  created () {
    this.username = localStorage.getItem('username');
    // 如果指定联系人
    this.chat_name = this.$route.query.chat_name;
    this.chat_room = this.chat_name > this.username ? `${this.username}_${this.chat_name}` : `${this.chat_name}_${this.username}`
    // 加入房间
    this.$socket.emit('group', this.chat_room);
    this.$http.post('http://localhost:3000/userInfo', { username: this.username }).then(response => {
      this.user_img = response.data.data.userImg; // 头像

      // 获取用户头像
      return this.$http.post('http://localhost:3000/userInfo', { username: this.chat_name });
    }).then(response => {
      this.chat_img = response.data.data.userImg; // 头像

      // 查找房间信息
      return this.$http.post('http://localhost:3000/chat', { chatRoom: this.chat_room });
    }).then(response => {
      if (response.data.status == 0) {
        if (!response.data.data) {
          // 创建房间信息
          const obj = {
            chatRoom: this.chat_room,
            userOne: this.username,
            userTwo: this.chat_name,
            imgOne: this.user_img,
            imgTwo: this.chat_img,
            chatTime: Date.now(),
          }
          this.$http.post('http://localhost:3000/users/chat', obj).then(response => {
            if (response.data.status == 0) { }
          })
        } else {
          this.record = response.data.data.chatContent;
          for (const item of this.record) {
            this.create_dom(item.content, item.name, item.user_img, item.time);
          }
        }
      }
      // 获取联系人列表
      return this.$http.post('http://localhost:3000/chat/user', { username: this.username })
    }).then(response => {
      if (response.data.data.length == 0) {
        this.isBlank = true;
      }
      this.contact_list = response.data.data;
      if (this.contact_list.length > 1) {
        this.contact_list.sort((a, b) => Number.parseInt(b.chatTime) - Number.parseInt(a.chatTime));
      }
      if (!this.$route.query.chat_name) {
        this.update(this.contact_list[0], 0);
      }
    })
  },
  mounted () {
    // 滑动页面
    this.$refs.container.onwheel = (event) => {
      if (this.$refs.container.clientHeight <= this.$refs.right_container.clientHeight) {
        return;
      }
      if (!!this.$refs.container.style.bottom == false) {
        this.$refs.container.style.bottom = 0;
      }
      if (event.wheelDelta > 0) {
        // 差值
        const des = Number.parseInt(this.$refs.container.clientHeight) - Number.parseInt(this.$refs.right_container.clientHeight);
        des + 48 + Number.parseInt(this.$refs.container.style.bottom) < 60 ?
          this.$refs.container.style.bottom = -des - 48 + 'px' :
          this.$refs.container.style.bottom = Number.parseInt(this.$refs.container.style.bottom) - 60 + 'px';
      } else {
        Number.parseInt(this.$refs.container.style.bottom) > -60 ?
          this.$refs.container.style.bottom = 0 :
          this.$refs.container.style.bottom = Number.parseInt(this.$refs.container.style.bottom) + 60 + 'px';
      }
    }
  },
  sockets: {
    mes ([content, username, user_img, time]) {
      this.create_dom(content, username, user_img, time);
      this.record.push({
        time: time,
        name: username,
        content: content,
        user_img: user_img
      })
      // 保存聊天记录
      const obj = {
        chatRoom: this.chat_room,
        chatTime: Date.now(),
        chatContent: this.record,
      }
      this.$http.post('http://localhost:3000/users/upchat', obj).then(response => {
        if (response.data.status == 1) {
          console.log('保存失败');
        }
      })
    }
  },
  methods: {
    submit () {
      if (!this.content) {
        return;
      }
      this.$socket.emit('message', [this.content, this.username, this.user_img, Date.now()]);
      this.content = '';
    },
    create_dom (content, username, user_img, time) {
      const li = document.createElement('li'),
        text = document.createElement('span'),
        img = document.createElement('img');
      if (username == this.username) {
        li.className = 'isme';
        li.appendChild(img);
        li.appendChild(text);
        img.src = this.user_img;
      } else {
        li.appendChild(img);
        li.appendChild(text);
        img.src = this.user_img;
      }
      text.innerText = content;
      this.$refs.container.appendChild(li);
    },
    update (item, index) {
      const list = this.$refs.list.children,
        list_len = list.length;
      for (let i = 0; i < list_len; i++) {
        if (index == i) {
          list[i].className = 'active';
        } else {
          list[i].className = '';
        }
      }

      this.chat_name = item.userOne == this.username ? item.userTwo : item.userOne;
      this.chat_img = item.userOne == this.username ? item.imgTwo : item.imgOne;

      // 删除节点
      const parent = this.$refs.container;
      const child = parent.children;
      for (let i = 0; i < child.length; i++) {
        parent.removeChild(child[i]);
      }

      this.chat_room = this.chat_name > this.username ? `${this.username}_${this.chat_name}` : `${this.chat_name}_${this.username}`
      // 加入房间
      this.$socket.emit('group', this.chat_room);
      // 查找房间信息
      this.$http.post('http://localhost:3000/chat', { chatRoom: this.chat_room }).then(response => {
        this.record = response.data.data.chatContent;
        for (const item of this.record) {
          this.create_dom(item.content, item.name, item.user_img, item.time);
        }
      })
    }
  }
}
</script>

<style lang="less">
html,
body {
  width: 100%;
  height: 100%;
  background-color: #333;
}

.chart_room {
  width: 1130px;
  height: 800px;
  margin: 50px auto 0;
  display: flex;
  background-color: #fff;

  .left {
    width: 250px;
    height: 100%;
    border-right: 1px solid #ccc;
    box-sizing: border-box;

    .left_header {
      width: 100%;
      height: 70px;
      background-color: #ff534c;
      display: flex;
      box-sizing: border-box;
      padding: 10px;

      img {
        width: 50px;
        height: 50px;
        margin-right: 10px;
      }
      h3 {
        color: #fff;
        font-weight: 400;
        font-size: 18px;
      }
    }
    .left_list {
      li {
        width: 100%;
        background-color: #f2f5f9;
        height: 40px;
        padding: 10px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        cursor: pointer;

        img {
          width: 20px;
          height: 20px;
          margin-right: 10px;
        }
        span {
          font-size: 13px;
        }
      }
      li.active {
        background-color: #d2e6f9;
        height: 50px;

        img {
          width: 30px;
          height: 30px;
        }
        span {
          font-size: 14px;
        }
      }
    }
  }
  .right {
    width: 880px;
    height: 100%;

    .right_header {
      width: 100%;
      height: 60px;
      background-color: #fafafa;
      display: flex;
      align-items: center;

      img {
        display: inline-block;
        width: 50px;
        height: 50px;
        margin: 0 20px;
      }
    }
    .right_container {
      width: 100%;
      height: 605px;
      padding: 20px;
      box-sizing: border-box;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
      position: relative;
      overflow: hidden;

      .content {
        width: 100%;
        min-height: 560px;
        position: absolute;
        margin: 10px 0;
        bottom: 0;
        left: 0;

        li {
          width: 90%;
          margin-bottom: 20px;
          float: left;
          display: flex;
          flex-direction: row;

          img {
            display: inline-block;
            width: 32px;
            height: 32px;
            margin: 0 10px;
          }
        }
        .isme {
          float: right;
          flex-direction: row-reverse;
        }
        span {
          max-width: 80%;
          padding: 5px 10px;
          border: 1px solid #ccc;
          border-radius: 10px;
          background-color: #fff;
        }
      }
    }
    .right_input {
      width: 100%;
      height: 130px;
      padding: 20px;
      box-sizing: border-box;
      background-color: #fff;
      position: relative;

      .input_textarea {
        width: 100%;
        height: 56px;
        outline: none;
        border: none;
      }
      .input_btn {
        border: 1px solid #ccc;
        background-color: #fff;
        padding: 5px 20px;
        border-radius: 5px;
        outline: none;
        cursor: pointer;
        position: absolute;
        right: 10px;
        bottom: 10px;
      }
    }
  }
}
.clearfix::after {
  clear: both;
  content: "";
  display: block;
}
</style>